<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>题目管理</el-breadcrumb-item>
      <el-breadcrumb-item>题目列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 导出表格按钮 -->
      <el-row style="margin-bottom: 15px" :gutter="120">
        <el-col :span="1">
          <el-button type="primary" @click="exportExcel">导出表格</el-button>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="exportExcel2">导出选中表格</el-button>
        </el-col>
      </el-row>

      <!-- 题目表格 -->
      <el-table
        :data="articleList"
        border
        stripe
        id="exportTab"
        @selection-change="handleSelectionChange"
        :default-sort = "{prop: 'publishDate', order: 'descending'}"
      >
        <el-table-column type="selection"></el-table-column>
        <!-- 展开行 -->
        <el-table-column type="expand" label="展开内容" width="80">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="2">
                <el-tag type="success">设计内容：</el-tag>
              </el-col>
              <el-col :span="12">
                <el-input type="textarea" :rows="10" placeholder="请输入内容" v-model="scope.row.content" readonly></el-input>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="题目id" prop="_id"></el-table-column>
        <el-table-column label="题目名称" prop="title"></el-table-column>
        <el-table-column label="指导老师" prop="Tauthor.username" sortable></el-table-column>
        <el-table-column label="指导老师邮箱" prop="Tauthor.email"></el-table-column>
        <el-table-column label="发布时间" prop="publishDate" sortable>
          <template slot-scope="scope">{{scope.row.publishDate | dateFormat}}</template>
        </el-table-column>
        <el-table-column label="审核状态" prop="checked" width="100">
          <!-- 审核状态作用域插槽 -->
          <template slot-scope="scpoe">
            <el-switch
              v-model="scpoe.row.checked"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchChange(scpoe.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 操作 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              size="mini"
              type="primary"
              class="el-icon-edit"
              @click="showEditDialog(scope.row._id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              size="mini"
              type="danger"
              class="el-icon-delete"
              @click="deleteArticle(scope.row._id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 隐藏的表格二 用于导出选中表格 -->
      <el-table
        :data="multipleSelection"
        border
        stripe
        id="exportTab2"
        @selection-change="handleSelectionChange"
        style="display: none"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="题目id" prop="_id"></el-table-column>
        <el-table-column label="题目名称" prop="title"></el-table-column>
        <el-table-column label="指导老师" prop="Tauthor.username"></el-table-column>
        <el-table-column label="指导老师邮箱" prop="Tauthor.email"></el-table-column>
        <el-table-column label="发布时间" prop="publishDate">
          <template slot-scope="scope">{{scope.row.publishDate | dateFormat}}</template>
        </el-table-column>
        <el-table-column label="审核状态" prop="checked" width="100">
          <!-- 审核状态作用域插槽 -->
          <template slot-scope="scpoe">
            <el-switch
              v-model="scpoe.row.checked"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchChange(scpoe.row)"
            ></el-switch>
            <el-tag style="display: none" v-if="scpoe.row.checked">通过</el-tag>
            <el-tag style="display: none" v-else>未通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 操作 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              size="mini"
              type="primary"
              class="el-icon-edit"
              @click="showEditDialog(scope.row._id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              size="mini"
              type="danger"
              class="el-icon-delete"
              @click="deleteArticle(scope.row._id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑题目对话框 -->
      <el-dialog
        title="编辑题目"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="restEditForm"
        top="100px"
      >
        <!-- 编辑题目表单 -->
        <el-form
          :model="editForm"
          :rules="editRules"
          ref="editFormRef"
          label-width="100px"
          label-position="top"
        >
          <el-form-item label="题目名称" prop="title">
            <el-input v-model="editForm.title"></el-input>
          </el-form-item>
          <el-form-item label="指导老师" prop="Tauthor">
            <!-- 选择器 -->
            <el-select v-model="editForm.Tauthor" placeholder="请选择">
              <!-- 循环私有数据中的老师数组 -->
              <el-option
                v-for="(item, index) in teachers"
                :key="index"
                :label="item.username"
                :value="item._id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题目内容" prop="content">
            <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="editForm.content"></el-input>
          </el-form-item>
        </el-form>
        <!-- 对话框底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editArticle">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
// 引入导出表格相关依赖
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

export default {
  data() {
    return {
      // 查询参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 数据总数
      total: 0,
      // 题目列表
      articleList: [],
      // 控制编辑题目对话框的显示与否
      editDialogVisible: false,
      // 编辑题目表单
      editForm: {
        title: '',
        Tauthor: '',
        content: ''
      },
      // 编辑题目表单验证规则
      editRules: {
        title: [{ required: true, message: '请输入题目名称', trigger: 'blur' }],
        Tauthor: [
          { required: true, message: '请选择指导老师', trigger: 'blur' }
        ]
      },
      // 老师列表数据
      teachers: [],
      // switch开关状态
      switchState: true,
      // 复选框选中后赋值到这个数据中,用于导出选中表格
      multipleSelection: []
    }
  },
  created() {
    this.getArticleList()
  },
  methods: {
    // 发送请求获取题目列表数据
    async getArticleList() {
      // 发送请求并解构
      const { data: res } = await this.$http.get('articles', {
        params: this.queryInfo
      })
      // 判断请求结果
      if (res.meta.status !== 200) {
        this.$message.error('获取题目列表失败')
      }
      // 请求成功,赋值
      this.articleList = res.data.records
      this.total = res.data.total
      console.log(this.articleList)
    },
    // 每页显示条数改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      // 重新获取题目列表
      this.getArticleList()
    },
    // 当前页码改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      // 重新获取题目列表
      this.getArticleList()
    },
    // 显示编辑题目对话框
    async showEditDialog(id) {
      // 根据id查询题目
      const { data: res } = await this.$http.get('articles/' + id)
      // 判断请求结果
      if (res.meta.status !== 200) {
        return this.$message.error('获取题目信息失败')
      }
      // 请求成功,给数据赋值
      console.log(res.data)
      this.editForm = res.data

      // 获取用户列表
      const { data: user } = await this.$http.get('users')
      // 过滤出老师数组
      const teachers = user.records.filter(item => {
        return item.role === 'teacher'
      })
      console.log(teachers)
      // 给私有数据的老师数组赋值
      this.teachers = teachers
      // 显示对话框
      this.editDialogVisible = true
    },
    // 编辑完确定提交
    editArticle() {
      // 表单预验证
      this.$refs.editFormRef.validate(async valid => {
        // 如果未通过
        if (!valid) {
          return this.$message.error('验证不通过')
        }
        // 验证通过
        console.log(this.editForm)
        // 发送请求
        const { data: res } = await this.$http.put(
          'articles/edit/' + this.editForm._id,
          this.editForm
        )
        // 判断请求结果
        if (res.meta.status !== 200) {
          return this.$message.error('修改题目信息失败')
        }
        // 请求成功
        // 重新获取题目列表,给出提示,关闭对话框
        this.getArticleList()
        this.$message.success('修改成功')
        this.editDialogVisible = false
      })
    },
    // 对话框关闭事件,重置表单
    restEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 根据id删除题目
    async deleteArticle(id) {
      // 确认框
      const confirmResult = await this.$confirm(
        '此操作将永久删除该题目, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果点击了确认,发送请求
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete('articles/delete/' + id)
        // 判断请求结果
        if (res.meta.status !== 200) {
          this.$message.error('删除失败')
        }
        // 删除成功,给出提示,重新加载题目列表
        this.$message.success('删除成功')
        this.getArticleList()
      } else {
        // 如果点击了取消
        this.$message.info('已取消了删除操作')
      }
    },
    // switch 开关change事件
    async switchChange(row) {
      console.log(row.checked, row._id)
      // 发送请求,更新审核状态
      const { data: res } = await this.$http.put('articles/check/' + row._id, {
        checked: row.checked
      })
      // 判断请求结果
      if (res.meta.status !== 200) {
        return this.$message.error('更新审核状态失败')
      }
      // 更新成功,给出提示
      this.$message.success('更新审核状态成功')
    },
    // 当表格复选框发生变化时会触发该事件
    handleSelectionChange(val) {
      // 将对应行的数据赋值到multipleSelection数组中
      // multipleSelection数组中的数据用于渲染一个隐藏的表格,用于导出选中的表格项
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },

    // 导出表格
    exportExcel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector('#exportTab'),
        xlsxParam
      )

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          '审核情况表.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    },

    // 导出表格2
    // 导出表格
    exportExcel2() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector('#exportTab2'),
        xlsxParam
      )

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          '审核情况表.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    }
  }
}
</script>
